<template>
  <div class="dept-container">
    <!-- 头部 -->
    <header class="header">
      <div class="header-content">
        <h1>🏢 部门管理</h1>
        <div class="header-actions">
          <button class="btn-back" @click="$router.push('/home')">🏠 返回首页</button>
          <button class="btn-logout" @click="handleLogout">🚪 退出</button>
        </div>
      </div>
    </header>

    <!-- 主内容 -->
    <main class="main-content">
      <!-- 操作栏 -->
      <div class="action-bar" v-if="userRole === 'admin'">
        <button class="btn-primary" @click="showCreateDialog">➕ 创建部门</button>
      </div>

      <!-- 部门列表 -->
      <div class="dept-list">
        <div v-if="loading" class="loading">⏳ 加载中...</div>
        
        <div v-else-if="departments.length === 0" class="empty">
          <p>暂无部门数据</p>
        </div>
        
        <div v-else class="dept-grid">
          <div v-for="dept in departments" :key="dept.id" class="dept-card">
            <div class="dept-header">
              <div class="dept-icon">🏢</div>
              <h3>{{ dept.name }}</h3>
            </div>
            
            <div class="dept-details">
              <div class="detail-item">
                <span class="label">描述：</span>
                <span>{{ dept.description || '无描述' }}</span>
              </div>
              <div class="detail-item">
                <span class="label">创建时间：</span>
                <span>{{ dept.created_at }}</span>
              </div>
            </div>
            
            <div class="dept-actions">
              <button class="btn-sm btn-view" @click="viewDepartment(dept)">
                👁️ 查看详情
              </button>
              <button 
                v-if="userRole === 'admin'" 
                class="btn-sm btn-edit" 
                @click="showEditDialog(dept)"
              >
                ✏️ 编辑
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 创建/编辑对话框 -->
    <div v-if="showDialog" class="dialog-overlay" @click.self="closeDialog">
      <div class="dialog">
        <div class="dialog-header">
          <h3>{{ isEdit ? '✏️ 编辑部门' : '➕ 创建部门' }}</h3>
          <button class="btn-close" @click="closeDialog">✕</button>
        </div>
        
        <div class="dialog-body">
          <div class="form-group">
            <label>部门名称 *</label>
            <input v-model="form.name" placeholder="请输入部门名称">
          </div>
          
          <div class="form-group">
            <label>部门描述</label>
            <textarea v-model="form.description" placeholder="请输入部门描述" rows="3"></textarea>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button class="btn-secondary" @click="closeDialog">取消</button>
          <button class="btn-primary" @click="handleSubmit" :disabled="submitting">
            {{ submitting ? '⏳ 提交中...' : '✅ 确定' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 详情对话框 -->
    <div v-if="showDetailDialog" class="dialog-overlay" @click.self="closeDetailDialog">
      <div class="dialog dialog-large">
        <div class="dialog-header">
          <h3>🏢 {{ currentDept?.name }} - 部门详情</h3>
          <button class="btn-close" @click="closeDetailDialog">✕</button>
        </div>
        
        <div class="dialog-body">
          <div class="dept-info">
            <h4>基本信息</h4>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">部门名称：</span>
                <span>{{ currentDept?.name }}</span>
              </div>
              <div class="info-item">
                <span class="label">部门描述：</span>
                <span>{{ currentDept?.description || '无描述' }}</span>
              </div>
              <div class="info-item">
                <span class="label">创建时间：</span>
                <span>{{ currentDept?.created_at }}</span>
              </div>
            </div>
          </div>
          
          <div class="dept-employees">
            <h4>部门员工（{{ currentDept?.user_count || 0 }}人）</h4>
            <div v-if="currentDept?.users?.length > 0" class="employee-list">
              <div v-for="user in currentDept.users" :key="user.id" class="employee-item">
                <div class="employee-avatar">{{ user.real_name ? user.real_name[0] : user.user[0] }}</div>
                <div class="employee-info">
                  <div class="employee-name">{{ user.real_name || user.user }}</div>
                  <div class="employee-role">{{ user.role_name }}</div>
                </div>
                <div class="employee-email">{{ user.email || '未填写邮箱' }}</div>
              </div>
            </div>
            <div v-else class="empty-employees">
              <p>暂无员工</p>
            </div>
          </div>
        </div>
        
        <div class="dialog-footer">
          <button class="btn-primary" @click="closeDetailDialog">关闭</button>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message" :class="['toast', messageType]">{{ message }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request.js'

const router = useRouter()

// 状态
const userRole = ref(localStorage.getItem('user_role') || 'employee')
const departments = ref([])
const loading = ref(false)
const showDialog = ref(false)
const showDetailDialog = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const message = ref('')
const messageType = ref('info')
const currentDept = ref(null)

// 表单数据
const form = ref({
  name: '',
  description: ''
})

onMounted(() => {
  loadDepartments()
})

// 加载部门列表
const loadDepartments = async () => {
  loading.value = true
  try {
    const res = await request.get('/department/list')
    if (res.data.code === 200) {
      departments.value = res.data.data.departments
    }
  } catch (error) {
    console.error('加载部门失败:', error)
    showToast('加载部门列表失败', 'error')
  } finally {
    loading.value = false
  }
}

// 查看部门详情
const viewDepartment = async (dept) => {
  try {
    const res = await request.get(`/department/detail/${dept.id}`)
    if (res.data.code === 200) {
      currentDept.value = res.data.data
      showDetailDialog.value = true
    }
  } catch (error) {
    showToast(error.response?.data?.message || '获取部门详情失败', 'error')
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  form.value = {
    name: '',
    description: ''
  }
  showDialog.value = true
}

// 显示编辑对话框
const showEditDialog = (dept) => {
  isEdit.value = true
  form.value = {
    id: dept.id,
    name: dept.name,
    description: dept.description || ''
  }
  showDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
}

const closeDetailDialog = () => {
  showDetailDialog.value = false
  currentDept.value = null
}

// 提交表单
const handleSubmit = async () => {
  if (!form.value.name.trim()) {
    showToast('请填写部门名称', 'error')
    return
  }
  
  if (isEdit.value) {
    await updateDepartment()
  } else {
    await createDepartment()
  }
}

// 创建部门
const createDepartment = async () => {
  submitting.value = true
  try {
    const res = await request.post('/department/create', form.value)
    if (res.data.code === 200) {
      showToast('创建成功', 'success')
      closeDialog()
      loadDepartments()
    }
  } catch (error) {
    showToast(error.response?.data?.message || '创建失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 更新部门
const updateDepartment = async () => {
  submitting.value = true
  try {
    const res = await request.put(`/department/update/${form.value.id}`, form.value)
    if (res.data.code === 200) {
      showToast('更新成功', 'success')
      closeDialog()
      loadDepartments()
    }
  } catch (error) {
    showToast(error.response?.data?.message || '更新失败', 'error')
  } finally {
    submitting.value = false
  }
}

// 退出登录
const handleLogout = async () => {
  if (!confirm('确定要退出登录吗？')) return
  
  try {
    await request.post('/user/logout')
  } catch (error) {
    console.error('退出失败:', error)
  } finally {
    localStorage.clear()
    router.push('/')
  }
}

// 显示提示消息
const showToast = (msg, type = 'info') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}
</script>

<style scoped>
.dept-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.header {
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.btn-back, .btn-logout {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: transform 0.2s;
}

.btn-back {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.btn-logout {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.main-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.action-bar {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 20px;
}

.btn-primary {
  padding: 10px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
}

.dept-list {
  background: white;
  padding: 20px;
  border-radius: 12px;
  min-height: 400px;
}

.loading, .empty {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 16px;
}

.dept-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.dept-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 24px;
  transition: transform 0.2s;
}

.dept-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dept-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.dept-icon {
  font-size: 32px;
}

.dept-header h3 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.dept-details {
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
  border-bottom: 1px solid #e0e0e0;
  font-size: 14px;
}

.detail-item .label {
  color: #666;
  font-weight: 600;
  margin-bottom: 4px;
}

.dept-actions {
  display: flex;
  gap: 8px;
}

.btn-sm {
  flex: 1;
  padding: 10px 12px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 600;
  transition: transform 0.2s;
}

.btn-view {
  background: #667eea;
  color: white;
}

.btn-edit {
  background: #f5576c;
  color: white;
}

.btn-sm:hover {
  transform: translateY(-2px);
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow: auto;
}

.dialog-large {
  max-width: 700px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.dialog-header h3 {
  margin: 0;
  font-size: 20px;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.dialog-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
  font-size: 14px;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  box-sizing: border-box;
  font-family: inherit;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.btn-secondary {
  padding: 10px 20px;
  background: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
}

/* 部门详情 */
.dept-info {
  margin-bottom: 24px;
}

.dept-info h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 16px;
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-item .label {
  font-weight: 600;
  color: #666;
  min-width: 100px;
}

.dept-employees h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 16px;
}

.employee-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.employee-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.employee-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  flex-shrink: 0;
}

.employee-info {
  flex: 1;
}

.employee-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.employee-role {
  font-size: 12px;
  color: #666;
}

.employee-email {
  font-size: 13px;
  color: #999;
}

.empty-employees {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

/* Toast消息 */
.toast {
  position: fixed;
  top: 80px;
  right: 20px;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.3s ease-out;
  z-index: 1000;
}

@keyframes slideIn {
  from {
    transform: translateX(400px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.toast.success {
  background: #d4edda;
  color: #155724;
}

.toast.error {
  background: #f8d7da;
  color: #721c24;
}
</style>

